/*
 * chardev2.c - Create an input/output character device
 */

#include <linux/atomic.h>
#include <linux/cdev.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/module.h>	/* Specifically, a module */
#include <linux/printk.h>
#include <linux/types.h>
#include <linux/uaccess.h>	/* for get_user and put_user */
#include <linux/version.h>

#include <asm/errno.h>
#include "my_ioctl_opt.h"

#define SUCCESS 0
#define DEVICE_NAME "char_dev"
#define BUF_LEN 80
#define MAJOR_NUM 100

enum {
    CDEV_NOT_USED,
    CDEV_EXCLUSIVE_OPEN,
};

/* Is the device open right now? Used to prevent concurrent access into
 * the same device
 */
static atomic_t already_open = ATOMIC_INIT(CDEV_NOT_USED);
static struct Data {
    char val_char;
    short val_short;
    int val_int;
}data;

static struct class* cls;

/* This is called whenever a process attempts to open the device file */
static int device_open(struct inode* inode, struct file* file)
{
    pr_info("device_open(%p)\n", file);

    try_module_get(THIS_MODULE);
    return SUCCESS;
}

static int device_release(struct inode* inode, struct file* file)
{
    pr_info("device_release(%p,%p)\n", inode, file);

    module_put(THIS_MODULE);
    return SUCCESS;
}

static long device_ioctl(struct file* file,	/* ditto */
    unsigned int ioctl_num,	/* number and param for ioctl */
    unsigned long ioctl_param)
{
    long ret = SUCCESS;

    /* We don't want to talk to two processes at the same time. */
    if (atomic_cmpxchg(&already_open, CDEV_NOT_USED, CDEV_EXCLUSIVE_OPEN))
        return -EBUSY;

    /* Switch according to the ioctl called */
    switch (ioctl_num) {
    case E_Get_Char: {
        char __user* buff = (char __user*)ioctl_param;
        ret = copy_to_user(buff, &data.val_char, 1);
        if (ret) {
            pr_err("ioctl E_Get_Char,  copy_to_user failed\n");
            goto out;
        }
        break;
    }
    case E_Set_Char: {
        char __user* buff = (char __user*)ioctl_param;
        ret = copy_from_user(&data.val_char, buff, 1);
        if (ret) {
            pr_err("ioctl E_Set_Char,  copy_to_user failed\n");
            goto out;
        }
        pr_info("ioctl E_Set_Char, data.val_char=%c\n",data.val_char);
        break;
    }
    case E_Get_Int: {
        char __user* buff = (char __user*)ioctl_param;
        ret = copy_to_user(buff, &data.val_int, sizeof(data.val_int));
        if (ret) {
            pr_err("ioctl E_Get_Int,  copy_to_user failed\n");
            goto out;
        }
        break;
    }
    case E_Set_Int: {
        char __user* buff = (char __user*)ioctl_param;
        ret = copy_from_user(&data.val_int, buff, sizeof(data.val_int));
        if (ret) {
            pr_err("ioctl E_Set_Int,  copy_to_user failed\n");
            goto out;
        }
        pr_info("ioctl E_Set_Int, data.val_int=0x%X\n",data.val_int);
        break;
    }
    }


out:
    /* We're now ready for our next caller */
    atomic_set(&already_open, CDEV_NOT_USED);

    return ret;
}

/* Module Declarations */

/* This structure will hold the functions to be called when a process does
 * something to the device we created. Since a pointer to this structure
 * is kept in the devices table, it can't be local to init_module. NULL is
 * for unimplemented functions.
 */
static struct file_operations fops = {
    .unlocked_ioctl = device_ioctl,
    .open = device_open,
    .release = device_release,	/* a.k.a. close */
};

/* Initialize the module - Register the character device */
static int __init chardev2_init(void)
{
    // init data
    data.val_char = 'a';
    data.val_short = 0x1234;
    data.val_int = 0x12345678;

    /* Register the character device (at least try) */
    int ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &fops);

    /* Negative values signify an error */
    if (ret_val < 0) {
        pr_alert("%s failed with %d\n",
            "Sorry, registering the character device ", ret_val);
        return ret_val;
    }

#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0)
    cls = class_create(DEVICE_FILE_NAME);
#else
    cls = class_create(THIS_MODULE, DEVICE_FILE_NAME);
#endif
    device_create(cls, NULL, MKDEV(MAJOR_NUM, 0), NULL, DEVICE_FILE_NAME);

    pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME);

    return 0;
}

/* Cleanup - unregister the appropriate file from /proc */
static void __exit chardev2_exit(void)
{
    device_destroy(cls, MKDEV(MAJOR_NUM, 0));
    class_destroy(cls);

    /* Unregister the device */
    unregister_chrdev(MAJOR_NUM, DEVICE_NAME);
}

module_init(chardev2_init);
module_exit(chardev2_exit);

MODULE_LICENSE("GPL");
